package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.GetQiniuUploadTokenService;
import com.yixun.qfbao.util.QiNiuUtil;
import com.yixun.qfbao.util.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zilong.liu
 * @date 2020-10-26
 *
 * desc:
 *     获取七牛凭证
 */
@Service
public class GetQiniuUploadTokenServiceImpl implements GetQiniuUploadTokenService {

	@Value(value = "qiniuAccessKey")
	private String qiniuAccessKey;
	
	@Value(value = "qiniuSecretKey")
	private String qiniuSecretKey;
	
	@Value(value = "qiniuBucket")
	private String qiniuBucket;
	
	
	/**
	 * 获取七牛上传凭证
	 * @param 0 先从redis获取
	 *  1、直接请求七牛接口
	 */
	@Override
	public String getQiniuUploadToken(int castRefersh) {
		
		if(0 == castRefersh) {
			Object uploadToken = RedisUtil.get("qiniu_uploadtoken");
			if (uploadToken != null) {
				return uploadToken.toString();
			}
		}
		return getUploadTokenFromQiniu();
	}

	/**
	 * 避免多个客户端同时请求导致出现的多token混乱问题
	 * @return
	 */
	private synchronized String getUploadTokenFromQiniu() {
//		Auth auth = Auth.create(qiniuAccessKey, qiniuSecretKey);
//		String upToken = getRealUpToken(auth.uploadToken(qiniuBucket));
		String upToken = QiNiuUtil.createUploadToken(qiniuBucket);
//		String upToken = auth.uploadToken(qiniuBucket);
		RedisUtil.setEx("qiniu_uploadtoken", upToken, 3600L, TimeUnit.SECONDS);
		return upToken;
	}
	
	/**
	 * 因为获取到的token前缀为qiniuAccessKey： 需要去掉
	 * 不一定有用
	 * @param upToken
	 * @return
	 */
	private String getRealUpToken(String upToken) {
		String prefix = "qiniuAccessKey:";
		int length = prefix.length();
		if(upToken.startsWith(prefix)) {
			return upToken.substring(length);
		}
		return upToken;
	}

	public static void main(String[] args) {
		GetQiniuUploadTokenServiceImpl g = new GetQiniuUploadTokenServiceImpl();
		System.out.println(g.getRealUpToken("qiniuAccessKey:123123123"));
	}
	
	
	public String getQiniuAccessKey() {
		return qiniuAccessKey;
	}

	public void setQiniuAccessKey(String qiniuAccessKey) {
		this.qiniuAccessKey = qiniuAccessKey;
	}

	public String getQiniuSecretKey() {
		return qiniuSecretKey;
	}

	public void setQiniuSecretKey(String qiniuSecretKey) {
		this.qiniuSecretKey = qiniuSecretKey;
	}

	public String getQiniuBucket() {
		return qiniuBucket;
	}

	public void setQiniuBucket(String qiniuBucket) {
		this.qiniuBucket = qiniuBucket;
	}

	
}
